use ggez::{Context, GameResult};
use ggez::graphics;
use crate::projectile::Projectile;
use crate::map::Map;
use std::time::Duration;

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TankState {
    Normal,
    Destroyed,
    Invincible,
}

#[derive(Debug, Clone, Copy)]
pub enum Direction {
    Up,
    Down,
    Left,
    Right,
}

#[derive(Debug, Clone, Copy)]
pub struct TankStateData {
    pub x: f32,
    pub y: f32,
    pub health: f32,
    pub max_health: f32,
    pub speed: f32,
    pub attack_range: f32,
    pub attack_damage: f32,
    pub attack_cooldown: f32,
    pub last_attack: Duration,
    pub color: graphics::Color,
    pub direction: Direction,
}

pub struct Tank {
    pub state: TankState,
    pub state_data: TankStateData,
}

impl Tank {
    pub fn new(
        health: f32,
        speed: f32,
        attack_range: f32,
        attack_damage: f32,
        attack_cooldown: f32,
        color: graphics::Color,
        x: f32,
        y: f32,
    ) -> Self {
        Self {
            state: TankState::Normal,
            state_data: TankStateData {
                x,
                y,
                health,
                max_health: health,
                speed,
                attack_range,
                attack_damage,
                attack_cooldown,
                last_attack: Duration::from_secs(0),
                color,
                direction: Direction::Up,
            },
        }
    }
    
    pub fn update(&mut self) {
        // 更新坦克状态
        if self.state_data.health <= 0.0 {
            self.state = TankState::Destroyed;
        }
    }
    
    pub fn move_up(&mut self) {
        self.state_data.y -= self.state_data.speed;
        self.state_data.direction = Direction::Up;
    }
    
    pub fn move_down(&mut self) {
        self.state_data.y += self.state_data.speed;
        self.state_data.direction = Direction::Down;
    }
    
    pub fn move_left(&mut self) {
        self.state_data.x -= self.state_data.speed;
        self.state_data.direction = Direction::Left;
    }
    
    pub fn move_right(&mut self) {
        self.state_data.x += self.state_data.speed;
        self.state_data.direction = Direction::Right;
    }
    
    pub fn attack(&mut self, projectiles: &mut Vec<Projectile>) {
        let now = Duration::from_secs(0); // 简化处理，实际应使用真实时间
        if (now - self.state_data.last_attack).as_secs_f32() >= self.state_data.attack_cooldown {
            let (dx, dy) = match self.state_data.direction {
                Direction::Up => (0.0, -1.0),
                Direction::Down => (0.0, 1.0),
                Direction::Left => (-1.0, 0.0),
                Direction::Right => (1.0, 0.0),
            };
            
            projectiles.push(Projectile::new(
                self.state_data.x,
                self.state_data.y,
                dx * self.state_data.attack_range,
                dy * self.state_data.attack_range,
                self.state_data.attack_damage,
            ));
            
            self.state_data.last_attack = now;
        }
    }
    
    pub fn take_damage(&mut self, damage: f32) {
        if self.state != TankState::Invincible {
            self.state_data.health -= damage;
        }
    }
    
    pub fn draw(&self, canvas: &mut graphics::Canvas, _ctx: &mut Context) -> GameResult {
        if self.state == TankState::Destroyed {
            return Ok(());
        }
        
        let tank_rect = graphics::Rect::new(self.state_data.x - 10.0, self.state_data.y - 10.0, 20.0, 20.0);
        let tank_mesh = graphics::Mesh::new_rectangle(
            _ctx,
            graphics::DrawMode::fill(),
            tank_rect,
            self.state_data.color,
        )?;
        
        canvas.draw(&tank_mesh, graphics::DrawParam::default());
        Ok(())
    }
    
    // AI感知函数
    pub fn perceive(&self, all_tanks: &[Tank], map: &Map) -> TankPerception {
        let mut allies = Vec::new();
        let mut enemies = Vec::new();
        
        for tank in all_tanks {
            if tank.state == TankState::Destroyed {
                continue;
            }
            
            // 简化处理：索引0为玩家（友军），其他为敌人
            if std::ptr::eq(tank, self) {
                continue; // 跳过自己
            } else if tank as *const _ as usize == all_tanks.as_ptr() as usize {
                allies.push(EnemyState {
                    x: tank.state_data.x,
                    y: tank.state_data.y,
                    health: tank.state_data.health,
                });
            } else {
                enemies.push(EnemyState {
                    x: tank.state_data.x,
                    y: tank.state_data.y,
                    health: tank.state_data.health,
                });
            }
        }
        
        TankPerception {
            self_state: self.state_data,
            allies,
            enemies,
            obstacles: vec![], // 简化处理
            powerups: vec![],  // 简化处理
        }
    }
    
    pub fn execute_action(&mut self, action: TankAction, projectiles: &mut Vec<Projectile>) {
        match action {
            TankAction::Move(direction) => match direction {
                Direction::Up => self.move_up(),
                Direction::Down => self.move_down(),
                Direction::Left => self.move_left(),
                Direction::Right => self.move_right(),
            },
            TankAction::Attack(target) => {
                // 简化处理，直接朝目标方向攻击
                let dx = target.x - self.state_data.x;
                let dy = target.y - self.state_data.y;
                let distance = (dx * dx + dy * dy).sqrt();
                
                if distance > 0.0 {
                    projectiles.push(Projectile::new(
                        self.state_data.x,
                        self.state_data.y,
                        dx / distance * self.state_data.attack_range,
                        dy / distance * self.state_data.attack_range,
                        self.state_data.attack_damage,
                    ));
                }
            },
            TankAction::Stay => {}, // 什么都不做
            TankAction::Retreat => {
                // 简化处理，向后移动
                match self.state_data.direction {
                    Direction::Up => self.move_down(),
                    Direction::Down => self.move_up(),
                    Direction::Left => self.move_right(),
                    Direction::Right => self.move_left(),
                }
            },
        }
    }
}

// AI相关结构体定义
#[derive(Debug, Clone, Copy)]
pub struct EnemyState {
    pub x: f32,
    pub y: f32,
    pub health: f32,
}

#[derive(Debug)]
pub struct TankPerception {
    pub self_state: TankStateData,
    pub allies: Vec<EnemyState>,
    pub enemies: Vec<EnemyState>,
    pub obstacles: Vec<Obstacle>,
    pub powerups: Vec<Powerup>,
}

#[derive(Debug)]
pub struct Obstacle {
    pub x: f32,
    pub y: f32,
    pub destructible: bool,
}

#[derive(Debug)]
pub struct Powerup {
    pub x: f32,
    pub y: f32,
    pub kind: PowerupType,
}

#[derive(Debug)]
pub enum PowerupType {
    Health,
    Speed,
    Damage,
    Invincible,
}

#[derive(Debug)]
pub enum TankAction {
    Move(Direction),
    Attack(Point),
    Stay,
    Retreat,
}

#[derive(Debug)]
pub struct Point {
    pub x: f32,
    pub y: f32,
}